// 环境配置
export const ENVIRONMENTS = {
  DEVELOPMENT: 'development',
  PRODUCTION: 'production',
  TEST: 'test'
};

// 手动环境开关（留空则自动判断；可填 'development' | 'production' | 'test'）
export const MANUAL_ENV = 'development';

// 环境配置映射
export const ENV_CONFIG = {
  [ENVIRONMENTS.DEVELOPMENT]: {
    name: '开发环境',
    apiBaseUrl: 'http://192.168.2.2:8080',
    wsUrl: 'ws://192.168.2.2:8080',
    debug: true,
    timeout: 30000,
    maxRetries: 5,
    retryInterval: 1000
  },
  [ENVIRONMENTS.PRODUCTION]: {
    name: '生产环境',
    apiBaseUrl: 'https://skillith.cn/api',
    wsUrl: 'wss://skillith.cn/api',
    debug: false,
    timeout: 15000,
    maxRetries: 3,
    retryInterval: 2000
  },
  [ENVIRONMENTS.TEST]: {
    name: '测试环境',
    apiBaseUrl: 'https://test.skillith.cn/api',
    wsUrl: 'wss://test.skillith.cn/ws',
    debug: true,
    timeout: 20000,
    maxRetries: 3,
    retryInterval: 1500
  }
};

// 获取当前环境
export const getCurrentEnvironment = () => {
  // 0) 显式手动开关
  if (MANUAL_ENV && ENV_CONFIG[MANUAL_ENV]) {
    return MANUAL_ENV;
  }

  // 1) 优先从本地存储获取
  const storedEnv = uni.getStorageSync('app_environment');
  if (storedEnv && ENV_CONFIG[storedEnv]) {
    return storedEnv;
  }
  
  // 2) 根据域名判断环境
  const hostname = (typeof window !== 'undefined' && window.location?.hostname) || '';
  if (hostname.includes('localhost') || hostname.includes('192.168.2.2')) {
    return ENVIRONMENTS.DEVELOPMENT;
  } else if (hostname.includes('test.')) {
    return ENVIRONMENTS.TEST;
  } else {
    return ENVIRONMENTS.PRODUCTION;
  }
};

// 获取当前环境配置
export const getCurrentConfig = () => {
  const env = getCurrentEnvironment();
  return ENV_CONFIG[env];
};

// 设置环境（本地覆盖）
export const setEnvironment = (env) => {
  if (ENV_CONFIG[env]) {
    uni.setStorageSync('app_environment', env);
    console.log(`环境已切换到: ${ENV_CONFIG[env].name}`);
    return true;
  }
  console.error(`无效的环境: ${env}`);
  return false;
};

// 获取所有可用环境
export const getAvailableEnvironments = () => {
  return Object.keys(ENV_CONFIG).map(key => ({
    key,
    ...ENV_CONFIG[key]
  }));
};

// 环境切换工具
export const switchEnvironment = (env) => {
  if (setEnvironment(env)) {
    // 重新加载页面以应用新配置
    uni.showModal({
      title: '环境切换',
      content: `已切换到${ENV_CONFIG[env].name}，是否重新加载页面？`,
      success: (res) => {
        if (res.confirm) {
          uni.reLaunch({
            url: '/pages/index/index'
          });
        }
      }
    });
    return true;
  }
  return false;
};
